<template>
  <div id="polar"></div>
</template>

<script>
import * as echarts from "echarts/core";
// Import TooltipComponent
import { PolarComponent, LegendComponent, TitleComponent, TooltipComponent } from "echarts/components";
import { BarChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";

export default {
  props: ["chartData", "collectData"],
  watch: {
    chartData() {
      if (this.chartData.length !== 0 && this.loading) {
        this.initChart();
        this.loading = false;
      }
    },
  },
  methods: {
    initChart() {
      // Register TooltipComponent
      echarts.use([PolarComponent, LegendComponent, TitleComponent, TooltipComponent, BarChart, CanvasRenderer]);
      const chartDom = document.getElementById("polar");
      this.myChart = echarts.init(chartDom);
      this.collectData.report = this.addStr(this.collectData.report, "\n", "：");
      this.option = {
        title: {
          show: true,
          right: 0,
          text: this.collectData.report + "数据获得于：\n" + this.collectData.report_at,
          textStyle: {
            fontSize: 12,
          },
        },
        angleAxis: {
          type: "category",
          data: this.chartData[0],
          scale: false,
          splitNumber: 5,
        },
        radiusAxis: {
          min: 0,
          max: 25,
          axisLabel: {
            formatter: (value) => value - 120,
          },
        },
        tooltip: {
          formatter: (params) => `${params.name}: ${params.value - 120}`,
        },
        polar: {},
        series: [
          {
            type: "bar",
            data: this.chartData[1].map((x) => x + 120),
            color: "#F53700",
            coordinateSystem: "polar",
            name: "平均干扰值",
            emphasis: {
              focus: "series",
            },
          },
        ],
        legend: {
          show: true,
          data: ["平均干扰值"],
          right: 20,
          bottom: 10,
        },
      };
      this.option && this.myChart.setOption(this.option);
    },
    addStr(oldStr, addItem, afterWhich) {
      // 在指定字符串后面添加指定字符串
      let strArr = oldStr.split(afterWhich);
      let resultArr = [];
      strArr.forEach((element) => {
        resultArr.push(element + afterWhich + addItem);
      });
      return resultArr.join("");
    },
  },
  data() {
    return {
      loading: true,
    };
  },
};
</script>
<style scoped>
#polar {
  width: 98%;
  height: 280px;
}
</style>
